#!/bin/bash

# Function to display usage
usage() {
  echo "本工具用于将sealos本地映像库（sealos images）中的映像导出为离线映像文件，"
  echo "保存在/root/offline_images目录中，以tar.gz为结尾"
  echo ""
  echo "Usage: $0 [-a] [-h] [-i string]"
  echo "  -a: 导出所有映像, -a参数可省略"
  echo "  -h: 显示本帮助信息"
  echo "  -i: 用于导出单个映像，参数为要导出的映像名称"
  exit 1
}

# Initialize variables
image_name=""
a_flag=0

# Process command-line options
while getopts 'ahi:' flag; do
  case "${flag}" in
    a) a_flag=1 ;; # Set a flag or perform an action for '-a' option
    h) usage ;;
    i) image_name="${OPTARG}" ;;
    *) usage ;;
  esac
done


# Run the 'sealos images' command and process its output
if [ -z $image_name ]; then
  imagelist=`sealos images | tail -n +2`
  if [ -z $imagelist ]; then
    echo "当前sealos映像库中不存在映像"
    exit 1
  fi
else
  imagelist=`sealos images | grep $image_name `
  if [ $? -ne 0 ]; then
    echo "找不到映像${image_name}, 请检查输入参数"
    exit 1
  fi
fi

mkdir -p /root/offline_images

while read line;
do
  echo $line
  sourcename=`echo $line | awk '{print $1":"$2}'`
  echo $sourcename

  outputname=`echo $sourcename | awk -F '/' '{print $3}' | tr '/:' '.' | sed 's/$/.tar.gz/'`
  echo $outputname

  sealos save -o /root/offline_images/${outputname} $sourcename

done <<< $imagelist

